import type { AxiosResponse } from 'axios'
import type { RouteRecordRaw } from 'vue-router'
import type { ILoginParams, IResponseAccount } from '@/types/api/index.js'
import type { IAccount, IButtonMenuRoleMap, IMenuVue, IRoleMap } from '@/types/index.js'
import type { IMenuRouteNode } from '@/types/store/user.js'
import { ElMessage } from 'element-plus'
import { sortBy } from 'lodash'
import { defineStore } from 'pinia'
import { userLoginAPI } from '@/api/user.js'
import { adminRoutes } from '@/router/adminRoutes.js'
import router from '@/router/index.js'

const useUserStore = defineStore('user', {
  state: () => {
    return {
      token: localStorage.getItem('TOKEN') as string, // token
      language: 'en', // 语言
      userInfo: localStorage.getItem('usetInfo')
        ? JSON.parse(localStorage.getItem('usetInfo') || '')
        : {}, // 用户信息
      menu: [] as IMenuRouteNode[], // 菜单
      RoleMap: [] as IRoleMap[], // 角色
      btns: [] as IButtonMenuRoleMap[], // 按钮
    }
  },
  actions: {
    // 设置用户角色信息
    setRoleMap(RoleMap: IRoleMap[]) {
      this.RoleMap = RoleMap
    },
    // 设置用户按钮信息
    setBtns(btns: IButtonMenuRoleMap[]) {
      this.btns = btns
    },
    // 国际化配置语言
    handleSetlang(lang = 'zh') {
      this.language = lang
    },
    // 配置token
    setToken(token: string) {
      localStorage.setItem('TOKEN', token)
      this.token = token
    },
    // 获取token
    getToken() {
      return localStorage.getItem('TOKEN')
    },
    // 设置用户信息
    setUserInfo(args = {}) {
      localStorage.setItem('userInfo', JSON.stringify(args))
      this.userInfo = args
    },
    // 用户登录
    async userLogin(args: ILoginParams | null) {
      const res = await userLoginAPI(args).catch(err => err) as AxiosResponse<IResponseAccount>
      const { success, data, message } = res
      if (success) {
        const { token, dev_Account } = data
        this.setToken(token)
        this.setBtns(dev_Account.ButtonMenuRoleMap)
        this.setUserInfo({
          Account: dev_Account.Account,
          Name: dev_Account.Name,
          Pwd: dev_Account.Pwd,
          Avater: data.AvatarURL,
        })
        this.setRoleMap(dev_Account.RoleMap)
        this.setMenu(dev_Account)
        return dev_Account
      }
      else {
        ElMessage.error(message)
      }
    },
    // 退出登录
    userExit() {
      this.setToken('')
      // this.setUserInfo();
      localStorage.clear()
    },
    // 配置菜单
    setMenu(AccountDatas: IAccount) {
      const addData: IMenuRouteNode[] = flatArrayToTree(AccountDatas.MenuVue, this.btns)
      const isAdmin = AccountDatas.RoleMap.some(val => val.RoleID === 'E01Admin')
      if (isAdmin) {
        addData.unshift(...adminRoutes)
        // console.log('isAdmin')
        // adminRoutes.forEach((val) => {
        //   if (val)
        //     router.addRoute(val as RouteRecordRaw)
        // })
      }
      addData.forEach(async (val) => {
        if (val)
          router.addRoute(val as RouteRecordRaw)
      })
      this.menu = addData
    },
  },
})
// 处理 菜单树
function flatArrayToTree(
  flatArray: IMenuVue[],
  btns: IButtonMenuRoleMap[] | null,
): IMenuRouteNode[] {
  const map = new Map<string, IMenuRouteNode>()

  // 类型守卫：确保 btns 是数组
  const getFilteredBtns = (menuCode: string): IButtonMenuRoleMap[] => {
    return btns?.filter(val => val.MenuCode === menuCode) || []
  }

  // 第一遍：创建所有节点映射
  flatArray.forEach((item) => {
    const mapValue: IMenuRouteNode = {
      path: item.Url,
      component: item.Component
        ? async () => {
          // Normalize component name to lowercase and handle Layout case
          let compName = item.Component
          if (compName.toLocaleLowerCase() === 'layout')
            compName = 'layout'
          // Try to import name.vue, then name/index.vue, fallback to 404
          return import(`@/views/${compName}.vue`)
            .catch(() => import(`@/views/${compName}/index.vue`)
              .catch(() => import('@/views/404/index.vue')))
        }
        : () => import('@/views/404/index.vue'),
      name: item.MenuCode, // 使用具有唯一性的MenuCode作为name。
      redirect: item.Redirect || undefined,
      hidden: !!item.Hidden,
      meta: {
        title: item.MenuName,
        icon: item.Ico,
        noCache: item.keepAlive,
        btns: getFilteredBtns(item.MenuCode),
        dicID: item.Remark2,
        index: Number(item.ViewSort),
        IsOpenWindow: item.IsOpenWindow,
        affix: item.MenuName === '首页',
        TargetFor: item.TargetFor,
        MenuCode: item.MenuCode,
        ParentCode: item.ParentCode,
        hidden: item.Hidden,
        alwaysShow: item.IsAllVisible,
      },
    }
    map.set(item.MenuCode, mapValue)
  })

  // 递归构建树
  const buildTree = (node: IMenuRouteNode): IMenuRouteNode => {
    flatArray.forEach((item) => {
      if (item.ParentCode && item.ParentCode === node.meta?.MenuCode) {
        const childNode = map.get(item.MenuCode)
        if (childNode) {
          if (!node.children) {
            node.children = []
          }
          node.children.push(buildTree(childNode))
        }
      }
    })

    // 使用 lodash 排序（确保类型安全）
    if (node.children) {
      node.children = sortBy(node.children, ['meta.index'])
    }
    return node
  }

  // 构建根节点树
  const rootNodes = flatArray.filter(item => !item.ParentCode)
    .map(rootNode => buildTree(map.get(rootNode.MenuCode)!))
  sortBy(rootNodes, 'meta.index')
  rootNodes.push({
    meta: {},
    path: '/:catchAll(.*)',
    redirect: '/404',
    hidden: true,
  })
  return rootNodes
}

export default useUserStore
